package com.starblink.home.subscription.child

import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.fragment.BaseTVMLazyLoadingFragment
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.extraOf
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.widget.recycler.RefresherAndListCombiner
import com.starblink.basic.route.RoutePage
import com.starblink.home.R
import com.starblink.home.databinding.CellSubsItemMainBinding
import com.starblink.home.databinding.CellSubsLoadingBinding
import com.starblink.home.databinding.FragmentSubsChildBinding
import com.starblink.home.subscription.cell.SubsLoadingCell
import com.starblink.home.subscription.cell.SubscriptionCell

/**
 *  Create by yuanl at 2023/10/8
 **/
class SubsChildFragment : BaseTVMLazyLoadingFragment<FragmentSubsChildBinding, SubsChildVM>() {

    companion object {

        fun newIns(type: Int?) = SubsChildFragment().apply {
            if (type != null) {
                arguments = bundleOf(
                    "type" to type
                )
            }
        }

    }

    private val adapter by lazyOnNone {
        MutableAdapter(viewModel.list).apply {
            addVhDelegate {
                SubscriptionCell(CellSubsItemMainBinding.inflate(layoutInflater, it, false),
                    brandMsgClick = {
                        val brand = it?.discountBrandMessage?.disCountBrandMessageF
                        viewModel.routeBrandDiscountState(brand?.id, brand?.discountChange, brand?.discount)
                    },
                    merchantMsgClick = {
                        viewModel.routeMerchantDiscountState(it?.discountStoreMessage?.discountStoreMessageF?.id, it?.discountStoreMessage?.discountStoreMessageF?.discountChange)
                    },
                    prdMsgClick = {
                        viewModel.routePrdDiscountState(requireContext(), it?.discountProductMessage?.discountProductMessageF?.id, it?.discountProductMessage?.discountProductMessageF?.discountChange)
                    }
                )
            }
            addVhDelegate {
                SubsLoadingCell(CellSubsLoadingBinding.inflate(layoutInflater, it, false))
            }
        }
    }

    private var lazyLoaded = false

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentSubsChildBinding = FragmentSubsChildBinding.inflate(layoutInflater)

    override fun onLazyInitData() {
        viewModel.requestData()
    }

    override fun initData() {
        viewModel.type = arguments?.getInt("type")
    }

    private val refreshCombiner by lazy {
        RefresherAndListCombiner(viewBinding.refresher, viewBinding.list)
    }

    override fun initView(view: View) {
        showStateSuccess()
//        showOrHideNavBarAnim(hashCode().toString(), viewBinding.list)
        viewBinding.refresher.bindHomeBar()
        refreshCombiner.onRefresh {
            loadInitData()
        }
        refreshCombiner.onLoadMore {
            viewModel.requestData(true)
        }
        viewBinding.list.layoutManager = LinearLayoutManager(context)
        viewBinding.list.adapter = adapter
        viewBinding.list.addItemDecoration(object : ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)
                outRect.bottom = 8.dp
            }
        })
        viewBinding.vEmpty.onBtnClick = {
            navigationTo(RoutePage.Search.PAGE_SEARCH) {
                extraOf(RoutePage.Search.ARG_SCENE to RoutePage.Search.SCENE.BRANDS.value)
            }
        }
        setEmptyViewText()
    }

    override fun initLoad() {

    }

    override fun startObserve() {
        viewModel.listDataLD.observe(this) {
            lazyLoaded = true
            refreshCombiner.finishRefresh()
            if (viewModel.pageNo == 1) {
                viewBinding.list.visibleOrGone(it)
                viewBinding.vEmpty.visibleOrGone(!it)
            }
            if (it) {
                refreshCombiner.finishLoadMore()
            } else {
                refreshCombiner.finishLoadMoreNoData(
                    textColor = color(com.starblink.basic.style.R.color.gu_text_tertiary),
                    lineColor = color(com.starblink.basic.style.R.color.gu_text_tertiary))
            }
            adapter.refreshAll()
        }
    }

    override fun spmPageId(): Int = SpmPageDef.PAGE_10235

    override fun spmPageParams(): Map<String, String> {
        val tabs = resources.getStringArray(R.array.subs_tabs)
        return mapOf(
            "tabName" to if (viewModel.type != null) tabs[viewModel.type!!] else tabs[0]
        )
    }

    fun onTabCheck() {
        if (lazyLoaded) {
            loadInitData()
        }
    }

    private fun loadInitData() {
        viewModel.requestData()
        refreshCombiner.setNoMoreData(false)
    }

    private fun setEmptyViewText() {
        viewBinding.vEmpty.text1 = "Discount Alerts!"
        viewBinding.vEmpty.btnText = "Follow Now"
        when(viewModel.type) {
            1 -> {
                viewBinding.vEmpty.text2 = "Follow your favorite brands to receive brand discount alerts. "
            }
            2 -> {
                viewBinding.vEmpty.text2 = "Follow your favorite stores to receive store discount alerts. "
            }
            3 -> {
                viewBinding.vEmpty.text2 = "Save your favorite items to receive item discount alerts. "
                viewBinding.vEmpty.btnText = "Save Now"
            }
            else -> {
                viewBinding.vEmpty.text2 = "Follow brands, stores, and items to make sure you don't miss out on any discount alerts."
            }
        }

    }

}